#include "rtthread.h"
#include "bf0_hal.h"
#include "drv_io.h"
#include "stdio.h"
#include "string.h"
#include <rtdevice.h>
#include "audio_server.h"
#include "mem_section.h"

static audio_client_t client_audio;
//#define AUDIO_WRITE_CACHE_SIZE (320*2)
#define AUDIO_READ_CACHE_SIZE  (320)

#define EVENT_MIC_RX    (1 << 0)
#define MIC_FRAME_LEN   (320 * 100) //1000ms for 16k samplerate

rt_event_t              mic_event;
int mic_rx_count = 0;
struct rt_ringbuffer    *rt_ringbuffer_fd;

static int audio_callback_record(audio_server_callback_cmt_t cmd, void *callback_userdata, uint32_t reserved)
{
    int fd = (int)callback_userdata;

    if (cmd == as_callback_cmd_data_coming)
    {
        /* get recording pcm data. */
        audio_server_coming_data_t *p = (audio_server_coming_data_t *)reserved;

        /* pcm data left shift 4 bits to increase volume. */
        //auido_gain_pcm((int16_t *)p->data, p->data_len, 1);

        //audio_write(client_audio, p->data,  p->data_len);// MIC_FRAME_LEN);   //直接输出到扬声器
#if 1
       rt_ringbuffer_put(rt_ringbuffer_fd, p->data, p->data_len);
       mic_rx_count += p->data_len;
        if (mic_rx_count >= MIC_FRAME_LEN)
        {
            mic_rx_count = 0;
            rt_event_send(mic_event, EVENT_MIC_RX);
        }
#endif
    }
    return 0;
}

void audio_init(void)
{
    audio_parameter_t param = {0};

    // 创建事件，用于音频处理中的同步
    mic_event = rt_event_create("audio_evt", RT_IPC_FLAG_FIFO);
    RT_ASSERT(mic_event);

    // 创建用于编码输入的环形缓冲区
    rt_ringbuffer_fd  = rt_ringbuffer_create(MIC_FRAME_LEN+320);    // two frame
    RT_ASSERT(rt_ringbuffer_fd);

    audio_server_set_private_volume(AUDIO_TYPE_LOCAL_MUSIC, 8);     //设置音量
    //BSP_GPIO_Set(10,  1, 1);        //GPIO_A10

    /* audio parameters. */
    param.write_bits_per_sample = 16;
    param.write_channnel_num = 1;
    param.write_samplerate = 16000; /* 16k sampling rate. */
    param.write_cache_size = MIC_FRAME_LEN;//AUDIO_WRITE_CACHE_SIZE;  /* write cache size */

    param.read_bits_per_sample = 16;
    param.read_channnel_num = 1;
    param.read_samplerate = 16000;  /* 16k sampling rate. */
    param.read_cache_size = AUDIO_READ_CACHE_SIZE;   /* read cache size */
   
    /* Start recording. */
    client_audio = audio_open(AUDIO_TYPE_LOCAL_RECORD, AUDIO_TXRX, &param, audio_callback_record, NULL);
    RT_ASSERT(client_audio);
}

int get_audio_ok(int16_t *p)
{
    rt_uint32_t evt = 0;
    rt_event_recv(mic_event, EVENT_MIC_RX, RT_EVENT_FLAG_OR | RT_EVENT_FLAG_CLEAR, RT_WAITING_FOREVER, &evt);
    if (evt & EVENT_MIC_RX)
    {
        rt_ringbuffer_get(rt_ringbuffer_fd,(uint8_t *)p, MIC_FRAME_LEN);
        
        audio_write(client_audio, (uint8_t *)p, MIC_FRAME_LEN); // MIC_FRAME_LEN);   回放音频
        rt_kprintf("out_speak_len %d\r\n",MIC_FRAME_LEN);
        return MIC_FRAME_LEN/2;
    }
    return 0;
}